package org.sction.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.sction.action.annotation.Parameter;
import org.sction.action.core.BaseAction;
import org.sction.manager.database.Criterion;
import org.sction.manager.database.CurrentPage;
import org.sction.manager.database.Criterion.CompareType;


/**
 * 继承自BaseAction 包含与qui页面框架配合使用的分页列表及需要的参数
 * 
 * @author sorc
 * @version 创建时间：2012-3-31 下午1:15:25
 * 
 * @see CurrentPage
 * @see BaseAction
 */
public class GridAction extends BaseAction {
	private static final Logger logger = Logger.getLogger(GridAction.class);
	@Parameter
	protected String id;
	@Parameter
	protected String name;
	// 采用的排序方式名称
	@Parameter("direction")
	protected String sord = "desc";
	// 用于排序的列名
	@Parameter("sort")
	protected String sidx;
	@Parameter("oper")
	protected String oper;
	@Parameter("nd")
	protected String nd; // 暂时不清楚啥用的
	// 单条件查询
	@Parameter("searchField")
	protected String searchField;
	@Parameter("searchString")
	protected String searchString;
	@Parameter("searchOper")
	protected String searchOper;
	// 是否请求搜索
	@Parameter("_search")
	protected boolean _search;

	// 多属性查询
	@Parameter("filters")
	protected String filters;
	// 多条件之间的关系
	protected String groupOp;

	// 行数
	@Parameter("pager.pageSize")
	protected Integer rows = 0;
	// 页码数
	@Parameter("pager.pageNo")
	protected Integer page = 0;
	// 数据行总数
	protected Integer record = 0;
	// 页码总数
	protected Integer total = 0;

	public Map<String, Object> refreshGridModel(
			CurrentPage<Map<String, Object>> cpage) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			if (cpage != null) {
				record = cpage.getTotalRecords();
				resultMap.put("pager.pageNo", cpage.getPageNum());
				resultMap.put("pageNo", cpage.getPageNum() - 1);
				resultMap.put("rows", cpage.getPageItems());
				resultMap.put("data", cpage.getData());
			}
			resultMap.put("pager.totalRows", record);
			resultMap.put("totalRows", record);
			resultMap.put("pager.pageSize", rows);
			resultMap.put("pageSize", rows);
			logger.debug("分页查询结果：" + resultMap);
			return resultMap;
		} catch (Exception e) {
			logger.error("refreshGridModel", e);
			return resultMap;
		}
	}

	public List<Criterion> generateSearchCriteriaFromFilters(String filters) {
		List<Criterion> criteria = new ArrayList<Criterion>();
		if (filters == null || filters.trim().equals("")) {
			criteria.add(this.generateSearchCriterion());
			return criteria;
		}
		// 解析Json
		JSONObject jsonObject = JSONObject.fromObject(filters);
		JSONArray rules = jsonObject.getJSONArray("rules");
		// 设置多条件之间的关系
		this.setGroupOp((String) jsonObject.get("groupOp"));
		for (Object obj : rules) {
			JSONObject rule = (JSONObject) obj;
			String field = rule.getString("field");
			String op = rule.getString("op");
			String data = rule.getString("data");
			// 生成Criterion
			Criterion criterion = this.generateSearchCriterion(field, data, op);

			// 将多条件的Criterion加入Lst(多属性)
			if (criterion != null) {
				criteria.add(criterion);
			}
		}
		return criteria;
	}

	public Criterion generateSearchCriterion(String searchField,
			String searchString, String searchOper) {
		Criterion criterion = null;
		// 如果searchField、searchString、searchOper均不为null，且searchString不为空字符串时，则创建Criterion
		if (searchField != null && searchString != null
				&& !searchString.trim().equals("") && searchOper != null) {
			if ("eq".equals(searchOper)) {
				criterion = Criterion.getEqualCriterion(searchField,
						searchString, null);
			} else if ("ne".equals(searchOper)) {
				criterion = Criterion.getCompareCriterion(CompareType.NE,
						searchField, searchString, null);
			} else if ("lt".equals(searchOper)) {
				criterion = Criterion.getCompareCriterion(CompareType.LT,
						searchField, searchString, null);
			} else if ("le".equals(searchOper)) {
				criterion = Criterion.getCompareCriterion(CompareType.LTE,
						searchField, searchString, null);
			} else if ("gt".equals(searchOper)) {
				criterion = Criterion.getCompareCriterion(CompareType.GT,
						searchField, searchString, null);
			} else if ("ge".equals(searchOper)) {
				criterion = Criterion.getCompareCriterion(CompareType.GTE,
						searchField, searchString, null);
			} else if ("bw".equals(searchOper)) {
				criterion = Criterion.getLikeCriterion(searchField,
						searchString + "%", null);
			} else if ("bn".equals(searchOper)) {
				criterion = Criterion.getNotLikeCriterion(searchField,
						searchString + "%", null);
			} else if ("ew".equals(searchOper)) {
				criterion = Criterion.getLikeCriterion(searchField, "%"
						+ searchString, null);
			} else if ("en".equals(searchOper)) {
				criterion = Criterion.getNotLikeCriterion(searchField, "%"
						+ searchString, null);
			} else if ("cn".equals(searchOper)) {
				criterion = Criterion.getLikeCriterion(searchField, "%"
						+ searchString + "%", null);
			} else if ("nc".equals(searchOper)) {
				criterion = Criterion.getNotLikeCriterion(searchField, "%"
						+ searchString + "%", null);
			}
		}
		return criterion;

	}

	public Criterion generateSearchCriterion() {
		return this.generateSearchCriterion(searchField, searchString,
				searchOper);
	}

	public Map<?, ?> getParameterSimpleMap() {
		Iterator<?> kit = parameterMap.keySet().iterator();
		Map<String, Object> param = new HashMap<String, Object>();
		while (kit.hasNext()) {
			String key = String.valueOf(kit.next());
			String v[] = (String[]) null;
			try {
				v = (String[]) parameterMap.get(key);
			} catch (Exception e) {
				continue;
			}
			if (v != null && v.length == 1)
				param.put(key, v[0]);
			else
				param.put(key, v);
		}
		return param;
	}

	public String getOrderStr() {
		if (this.sidx != null && !this.sidx.trim().equals("")) {
			String[] fields = this.sidx.split(",");
			String ordstring = " order by ";
			for (int i = 0; i < fields.length; i++) {
				String filed = fields[i];
				ordstring += (i == 0 ? (filed + " " + this.sord) : ("," + filed
						+ " " + this.sord));
			}
			return ordstring + " ";
		} else {
			return "";
		}
	}

	public String getOrderStr(String od) {
		if (this.sidx != null && !this.sidx.trim().equals("")) {
			return (" order by " + od + " " + this.sidx + " " + this.sord + " ");
		} else {
			return " order by " + od;
		}
	}

	public String getGroupOp() {
		return groupOp;
	}

	public void setGroupOp(String groupOp) {
		this.groupOp = groupOp;
	}

	public Integer getRows() {
		return rows;
	}

	public void setRows(Integer rows) {
		this.rows = rows;
	}

	public Integer getPage() {
		return page;
	}

	public void setPage(Integer page) {
		this.page = page;
	}

	public boolean getSearch() {
		return _search;
	}

	public void setSearch(boolean _search) {
		this._search = _search;
	}

	public String getFilters() {
		return filters;
	}

	public void setFilters(String filters) {
		this.filters = filters;
	}

}
